//
//  ICRedPacketSingleViewController.m
//  ICome
//
//  Created by 席鹏飞 on 2016/11/8.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICRedPacketSingleViewController.h"
#import "ICRedPacketInputView.h"
#import "NSMutableAttributedString+Extension.h"
#import "ZYKeyboardUtil.h"
#import "NSString+Extension.h"
#import "ICRedPacketPasswordViewController.h"
#import "ICRedPacketPayPasswordView.h"
#import "ICSendRedPacketModel.h"
#import "ICRedPacketNetworkManager.h"
#import "ICHeaderFile.h"

#define AmountDigit 5

@interface ICRedPacketSingleViewController () <ICRedPacketPayPasswordViewDelegate>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) ICRedPacketInputView *amountInputView;
@property (nonatomic, strong) ICRedPacketInputView *messageInputView;
@property (nonatomic, strong) UILabel *totalWorkPoint;
@property (nonatomic, strong) UIButton *sendButton;
@property (nonatomic, strong) UILabel *bottomPrompt;
@property (nonatomic, strong) ZYKeyboardUtil *keyboardUtil;
@property (nonatomic, strong) ICRedPacketPayPasswordView *payPasswordView;
@property (nonatomic, strong) ICSendRedPacketModel *model;
@property (nonatomic, strong) NSString *groupId;
@end

@implementation ICRedPacketSingleViewController

- (void)dealloc {
    [self removeObserver];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.groupId = self.parameterDictionary[@"groupId"];
    
    [self setUI];
    [self setNav];
    [self setTap];
    [self setKeyboardUtil];
    [self getData];
    [self addObserver];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNavBackgroundColor:NE_REDPACKET_BACKGROUND_COLOR];
    [self setNavShadowColor:NE_REDPACKET_BACKGROUND_COLOR];
}

#pragma mark - private methods

// 设置页面布局
- (void)setUI {
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [self.amountInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView.mas_top).offset(25);
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.height.mas_equalTo(45);
    }];
    [self.messageInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.amountInputView.mas_bottom).offset(15);
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.height.mas_equalTo(65);
    }];
    [self.totalWorkPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.messageInputView.mas_bottom).offset(40);
        make.left.equalTo(self.messageInputView.mas_left);
        make.right.equalTo(self.messageInputView.mas_right);
        make.height.mas_equalTo(30);
    }];
    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.totalWorkPoint.mas_bottom).offset(40);
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.height.mas_equalTo(45);
    }];
    [self.bottomPrompt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom).offset(-25);
    }];
}
// 设置navigation
- (void)setNav {
    self.title = @"发红包";
    
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamedFromiComeSDKBundle:@"App_back_white"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction:)]];
}
// 设置键盘取消事件
- (void)setTap {
    WEAKSELF;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf.view endEditing:YES];
        
        CGFloat height = [weakSelf.messageInputView.inputTextView.placeholder sizeWithMaxWidth:weakSelf.messageInputView.inputTextViewWidth andFont:[UIFont systemFontOfSize:16]].height;
        CGFloat textViewHeight = [weakSelf.messageInputView.inputTextView.text sizeWithMaxWidth:weakSelf.messageInputView.inputTextViewWidth andFont:[UIFont systemFontOfSize:16]].height;
        if (textViewHeight > height) {
            [weakSelf.messageInputView.inputTextView scrollToBottom];
        }
    }];
    [self.view addGestureRecognizer:tap];
}
// 设置键盘
- (void)setKeyboardUtil {
    WEAKSELF;
    self.keyboardUtil = [[ZYKeyboardUtil alloc] init];
    [self.keyboardUtil setAnimateWhenKeyboardAppearAutomaticAnimBlock:^(ZYKeyboardUtil *keyboardUtil) {
        [keyboardUtil adaptiveViewHandleWithController:weakSelf adaptiveView:weakSelf.amountInputView.inputTextField, weakSelf.messageInputView.inputTextView, nil];
    }];
}
// 网络请求
- (void)getData {
    self.amountInputView.contentDict = @{@"left":@"金额",
                                         @"right":@"工分"};
    self.messageInputView.contentDict = @{@"left":@"留言",
                                          @"right":@""};
}

- (void)addObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextChanged:) name:UITextFieldTextDidChangeNotification object:self.amountInputView.inputTextField];
}

- (void)removeObserver {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)textFieldTextChanged:(NSNotification *)notification {
    UITextField *textField = notification.object;
    if (textField.text.length > AmountDigit) {
        self.amountInputView.inputTextField.text = [textField.text substringToIndex:AmountDigit];
    }
    NSString *workPoint = [self getTotalPoint:self.amountInputView.inputTextField.text];
    self.totalWorkPoint.attributedText = [self showWorkPoint:workPoint];

    self.sendButton.enabled = (self.amountInputView.inputTextField.text.length > 0);
    if (self.sendButton.isEnabled) {
        [self.sendButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:1.0] forState:UIControlStateNormal];
    }else {
        [self.sendButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.4] forState:UIControlStateNormal];
    }
}

- (NSString *)getTotalPoint:(NSString *)point {
    return [NSString stringWithFormat:@"%.2f", [point floatValue]];
}

- (NSMutableAttributedString *)showWorkPoint:(NSString *)point {
    NSMutableAttributedString *text = [NSMutableAttributedString attributedString:@[@"总计： ", point, @"  工分"] colors:@[ICRGB(0x000000), ICRGB(0xf65b5b), ICRGB(0x000000)] fonts:@[ICFont(16.0 * Level), ICFont(30.0 * Level), ICFont(16.0 * Level)]];
    return text;
}

- (void)pushToRedPacketPasswordViewController {
    UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketPasswordViewController:nil];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)inputViewResignFirstResponder {
    [self.amountInputView.inputTextField resignFirstResponder];
    [self.messageInputView.inputTextView resignFirstResponder];
}

#pragma mark - event response

- (void)leftButtonAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)sendRedPacketBtnClicked:(UIButton *)sender {
    [self inputViewResignFirstResponder];
    if ([self.amountInputView.inputTextField.text intValue] == 0) {
        [MBProgressHUD showError:@"金额必须大于0"];
        return;
    }
    
    WEAKSELF
    [MBProgressHUD showProcessingActivityView:self.view];
    NSDictionary *param = @{@"eId":[ICUser currentUser].eId};
    // 检查红包密码是否已设置
    [[ICRedPacketNetworkManager sharedInstance] checkRedPacketPasswordWithParam:param success:^(id object) {
        //[MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if ([[object objectForKey:@"data"] intValue] == 1) { //已设置
            weakSelf.payPasswordView = [[ICRedPacketPayPasswordView alloc] init];
            weakSelf.payPasswordView.totalPoint = [weakSelf getTotalPoint:weakSelf.amountInputView.inputTextField.text];
            weakSelf.payPasswordView.delegate = weakSelf;
            [weakSelf.payPasswordView showInView:App_RootCtr.view];
        }else if ([[object objectForKey:@"data"] intValue] == 0) { //未设置
            [weakSelf pushToRedPacketPasswordViewController];
        }
    } failure:^(NSError *error) {
       // [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:error.domain];
    }];
}

#pragma mark - ICRedPacketPayPasswordViewDelegate
// 忘记密码
- (void)forgetPWDBtnClicked {
    [self.payPasswordView close];
    [self pushToRedPacketPasswordViewController];
}
// 确认
- (void)doneBtnClicked:(NSString *)password {
    if ([self getPasswordErrorCount] >= 3) {
        [self forgetPWDBtnClicked];
        return;
    }
    
    WEAKSELF
    NSString *message = self.messageInputView.inputTextView.text;
    NSString *placeholder = self.messageInputView.inputTextView.placeholder;
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [MBProgressHUD showProcessingActivityView:window];
    NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                            @"type":@1, //单人对单人
                            @"gId":self.groupId,
                            @"count":@1,
                            @"sum":[NSNumber numberWithDouble:(double)[self.amountInputView.inputTextField.text doubleValue]],
                            @"message":message.length > 0 ? message : placeholder,
                            @"password":password};
    // 发送红包
    [[ICRedPacketNetworkManager sharedInstance] sendRedPacketWithParam:param success:^(id object) {
        //[MBProgressHUD hideAllHUDsForView:window animated:YES];
        [MBProgressHUD hideHUDForView:window animated:YES];
        weakSelf.model = [ICSendRedPacketModel mj_objectWithKeyValues:[object objectForKey:@"data"]];
        [weakSelf.payPasswordView close];
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationSendRedPacketNotification object:weakSelf.model];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        //[MBProgressHUD hideAllHUDsForView:window animated:YES];
        [MBProgressHUD hideHUDForView:window animated:YES];
        if (error.code == 1100) { //密码错误
            [weakSelf savePasswordErrorCount];
            [weakSelf.payPasswordView clearThePassword];
            [MBProgressHUD showError:@"密码错误"];
        }else if (error.code == 8100) { //工分不足
            [MBProgressHUD showError:@"工分不足"];
        }else {
            [MBProgressHUD showError:error.domain];
        }
    }];
}

- (void)savePasswordErrorCount {
    NSInteger count = [self getPasswordErrorCount]+1;
    [[NSUserDefaults standardUserDefaults] setInteger:count forKey:@"passwordErrorCount"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSInteger)getPasswordErrorCount {
    NSInteger passwordErrorCount = [[NSUserDefaults standardUserDefaults] integerForKey:@"passwordErrorCount"];
    return passwordErrorCount;
}

#pragma mark - Getter

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

- (ICRedPacketInputView *)amountInputView {
    if (!_amountInputView) {
        _amountInputView = [[ICRedPacketInputView alloc] init];
        _amountInputView.inputTextField.placeholder = @"金额必须大于0";
        _amountInputView.inputTextField.keyboardType = UIKeyboardTypeNumberPad;
        [self.scrollView addSubview:_amountInputView];
    }
    return _amountInputView;
}

- (ICRedPacketInputView *)messageInputView {
    if (!_messageInputView) {
        _messageInputView = [[ICRedPacketInputView alloc] init];
        _messageInputView.inputTextView.placeholder = @"节节高升，再创佳绩!";
        [self.scrollView addSubview:_messageInputView];
    }
    return _messageInputView;
}

- (UILabel *)totalWorkPoint {
    if (!_totalWorkPoint) {
        _totalWorkPoint = [[UILabel alloc] init];
        _totalWorkPoint.attributedText = [self showWorkPoint:@"0.00"];
        _totalWorkPoint.textAlignment = NSTextAlignmentCenter;
        [self.scrollView addSubview:_totalWorkPoint];
    }
    return _totalWorkPoint;
}

- (UIButton *)sendButton {
    if (!_sendButton) {
        _sendButton = [[UIButton alloc] init];
        [_sendButton setTitle:@"发送红包" forState:UIControlStateNormal];
        [_sendButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.4] forState:UIControlStateNormal];
        _sendButton.titleLabel.font = ICFont(17.0 * Level);
        [_sendButton setBackgroundImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_done"] forState:UIControlStateNormal];
        [_sendButton addTarget:self action:@selector(sendRedPacketBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:_sendButton];
        _sendButton.enabled = NO;
    }
    return _sendButton;
}

- (UILabel *)bottomPrompt {
    if (!_bottomPrompt) {
        _bottomPrompt = [[UILabel alloc] init];
        _bottomPrompt.textAlignment = NSTextAlignmentCenter;
        _bottomPrompt.text = @"未领取的红包，将于24小时后退回";
        _bottomPrompt.textColor = ICRGB(0x828282);
        _bottomPrompt.font = ICFont(14.0 * Level);
        [self.scrollView addSubview:_bottomPrompt];
    }
    return _bottomPrompt;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
